import os

from django import template
from django.conf import settings
from django.utils.safestring import mark_safe

from apps.account.models import Account
from apps.blog.models import Article, Category

register = template.Library()


@register.simple_tag
def index_hot_verse():
    """首页热门文章诗句"""
    return mark_safe('夕殿萤飞思悄然，孤灯挑尽未成眠。<br />迟迟钟鼓初长夜，耿耿星河欲曙天。')


@register.simple_tag
def site_url(request):
    """站点域名"""
    url = request.get_raw_uri()
    return url.split('?', 1)[0]


@register.simple_tag
def site_title():
    """站点标题"""
    return "入迷生活"


@register.simple_tag
def site_logo():
    """站点logo"""
    return mark_safe('dark.night')


@register.simple_tag
def webmaster():
    """站长"""
    return "皓月当空"


@register.simple_tag
def webmaster_sign():
    """站长签名"""
    return mark_safe('明月照高楼，流光正徘徊。')


@register.inclusion_tag('common/index-hot-article.html')
def index_hot_article():
    """首页热门文章"""
    articles = Article.objects.order_by('-up_count')
    return {
        "articles": articles[0:settings.INDEX_HOT_ARTICLE_COUNT]
    }


@register.simple_tag
def visitor_list():
    """侧边访客列表"""
    accounts = Account.objects.filter(is_staff=False).order_by('-last_login')[0:settings.INDEX_VISITOR_COUNT]
    html = ''
    for account in accounts:
        html += f'<dd><a href="javasript:;"><img src="{account.avatar}"/><cite>{account.username}</cite></a></dd>'
    return mark_safe(html)


@register.simple_tag
def category_list(type):
    """侧边分类列表"""
    categories = Category.objects.all()
    html = ''
    if not type in ['pc', 'phone']:
        return ''
    for index, article in enumerate(categories):
        if type == 'pc':
            html += f'<li data-index="{index + 2}"><a href="{article.get_absolute_url()}">{article.name}</a></li>'
        else:
            html += f'<a href="{article.get_absolute_url()}">{article.name}</a>'
    return mark_safe(html)


def __get_config(name):
    value = os.environ.get(name, getattr(settings, name, None))

    return value


@register.filter
def get_config(key):
    """配置文件"""
    return __get_config(key)
